{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer=size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                for n in range(num_layers):\n",
    "                    (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                        cell_fw = cells(size_layer // 2),\n",
    "                        cell_bw = cells(size_layer // 2),\n",
    "                        inputs = encoder_embedded,\n",
    "                        sequence_length = self.X_seq_len,\n",
    "                        dtype = tf.float32,\n",
    "                        scope = 'bidirectional_rnn_%d'%(n))\n",
    "                    encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "                    \n",
    "                bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "                bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "                bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "                last_state = tuple([bi_lstm_state] * num_layers)\n",
    "                last_output = tf.concat((out_fw,out_bw), -1)\n",
    "\n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-83d9d0d26920>:11: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-83d9d0d26920>:36: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-83d9d0d26920>:50: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-83d9d0d26920>:60: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 27771, 27771, 27771, 13502, 13502, 30219, 30219, 28610,\n",
       "          17336, 17336,  7755, 29745,  4459,  4459,  4459,  4459, 25779,\n",
       "          25779,  2263, 10845, 10845, 10680, 27817, 27817, 21931, 26562,\n",
       "          26562, 27719, 27719, 27719, 27479, 27479, 27479, 21668, 31759,\n",
       "          31759]],\n",
       " \n",
       "        [[    1, 31388, 10962, 13242, 11317, 11317, 11317, 11320, 11320,\n",
       "          15165, 16966, 16966,  5524,  8865,  8865, 19347, 30700, 30700,\n",
       "           6930, 30700, 30700, 30700,  6118,  6749, 23158, 23158, 23158,\n",
       "          22782, 22782, 12943, 15284, 15284, 11040, 11849, 11849,   398,\n",
       "            398]],\n",
       " \n",
       "        [[    1, 29379, 29379,  8504, 24196,  6459,  6459,  6459,  4381,\n",
       "           4381, 12318, 12318, 24130, 24130, 24130, 17680, 13838, 13838,\n",
       "           7512, 28951, 28951,  8979,  8979,  8979, 14612, 14612, 11896,\n",
       "          11896, 11896, 11425, 11425, 27536, 27536, 13572, 30639, 30639,\n",
       "          31777]],\n",
       " \n",
       "        [[    1, 23575,  3828, 23575, 27489, 27489, 17036,  8848, 28728,\n",
       "           2015, 14827,  2499,  9591,  2499,  9591,  2203, 14518,  2203,\n",
       "          18316, 28399, 21188, 21188, 21188,  8308,  8308,  8772,  8772,\n",
       "           8772, 10045, 25825, 12010, 12010, 12010, 17731, 17731, 12010,\n",
       "          30507]],\n",
       " \n",
       "        [[    1, 30853, 31178,  4576,  4576, 18256, 19260, 20354,  8851,\n",
       "           8851, 20609, 20609, 20609, 20609, 24717, 24717, 24717, 24717,\n",
       "          18291,   154, 16987,   154,   154, 16987,  7547, 15925, 18382,\n",
       "          27810, 27810, 26893, 11768, 11768, 24770, 18279, 18279, 18279,\n",
       "          20619]],\n",
       " \n",
       "        [[    1, 17901, 24351, 24351,  7508, 25815, 25815, 23409, 23409,\n",
       "          23409, 16821,  6340,  6340,  6340,   983,   983,  7609,  7609,\n",
       "          21496, 10266, 10266, 29705, 23822,  4694, 23016, 23016, 25639,\n",
       "          25639, 25639, 13645, 20605, 20605, 11233, 11233,  1696, 26848,\n",
       "          26848]],\n",
       " \n",
       "        [[    1,  5208,  5798,  5798,  5798,  9590,  9590,   985,  7680,\n",
       "           7680, 26237, 29803,   293, 25501,   293,   764,  8183, 22479,\n",
       "          22479, 28099, 28099, 28099,   958,   958,  3836,  3836,   958,\n",
       "           1862,  1862,  1862,  1862,  1862,  1785,  1785,  1785,  8853,\n",
       "           8853]],\n",
       " \n",
       "        [[    1, 21904, 16507, 16507,  4301, 10294, 11584, 11256,  6648,\n",
       "           6648,  5542,  7420,  7420, 28761, 28761, 13013, 10833, 10833,\n",
       "          10833, 20438, 21904, 21904,  6958,  6958, 10309, 29560, 29560,\n",
       "          29560,  6647,  6647,   187,   187, 27846, 27846, 27846, 20770,\n",
       "          25509]],\n",
       " \n",
       "        [[    1, 29997,  3005,  3005, 18419, 23122, 23122, 18419, 18419,\n",
       "            214, 11331,  9349,  9349,  9349,  9349, 21510, 21256, 21256,\n",
       "          21256,  1196,  3563,  3563, 27767, 27767, 27767, 27767, 13086,\n",
       "          13086, 13086, 13086, 13086, 13086, 27877, 27877, 27877, 27877,\n",
       "           1872]],\n",
       " \n",
       "        [[    1, 28313, 28313, 17169, 17169, 14464, 17796, 17796,  2428,\n",
       "           2428,  2428, 10442,  2179,  2179, 17302,  5220,  5220,  3163,\n",
       "           3163, 11436, 11436, 11436, 11436,  6955, 28976, 28976, 19811,\n",
       "          13937, 13937, 11414, 11414, 11414, 11414,  1161,  4585,  4585,\n",
       "          13007]]], dtype=int32), 10.373442, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:25<00:00,  2.10it/s, accuracy=0.142, cost=6.19]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.63it/s, accuracy=0.134, cost=6.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.770929, training avg acc 0.127108\n",
      "epoch 1, testing avg loss 6.136930, testing avg acc 0.154804\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.161, cost=5.38]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.70it/s, accuracy=0.145, cost=5.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 5.775694, training avg acc 0.165919\n",
      "epoch 2, testing avg loss 5.676009, testing avg acc 0.168100\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:59<00:00,  2.01it/s, accuracy=0.185, cost=4.85]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.67it/s, accuracy=0.151, cost=5.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.274958, training avg acc 0.183518\n",
      "epoch 3, testing avg loss 5.502923, testing avg acc 0.172098\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:59<00:00,  2.01it/s, accuracy=0.213, cost=4.41]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.77it/s, accuracy=0.167, cost=5.64]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 4.925426, training avg acc 0.198812\n",
      "epoch 4, testing avg loss 5.410206, testing avg acc 0.173893\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:59<00:00,  2.01it/s, accuracy=0.24, cost=4.09] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.74it/s, accuracy=0.14, cost=5.62] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.646709, training avg acc 0.214111\n",
      "epoch 5, testing avg loss 5.418049, testing avg acc 0.175081\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.269, cost=3.79]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.74it/s, accuracy=0.134, cost=5.8] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.422307, training avg acc 0.229600\n",
      "epoch 6, testing avg loss 5.488710, testing avg acc 0.172909\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.316, cost=3.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.77it/s, accuracy=0.183, cost=5.61]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.244913, training avg acc 0.244274\n",
      "epoch 7, testing avg loss 5.536698, testing avg acc 0.170339\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.305, cost=3.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.75it/s, accuracy=0.167, cost=5.68]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.089472, training avg acc 0.259415\n",
      "epoch 8, testing avg loss 5.615686, testing avg acc 0.169679\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.346, cost=3.28]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.72it/s, accuracy=0.118, cost=6.03]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 3.951070, training avg acc 0.274483\n",
      "epoch 9, testing avg loss 5.735856, testing avg acc 0.166184\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.346, cost=3.17]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.73it/s, accuracy=0.161, cost=6.02]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 3.842838, training avg acc 0.286022\n",
      "epoch 10, testing avg loss 5.817304, testing avg acc 0.164979\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:57<00:00,  2.01it/s, accuracy=0.387, cost=2.95]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.71it/s, accuracy=0.188, cost=6.05]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.730789, training avg acc 0.299559\n",
      "epoch 11, testing avg loss 5.864305, testing avg acc 0.163374\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [13:00<00:00,  2.00it/s, accuracy=0.421, cost=2.82]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.71it/s, accuracy=0.177, cost=6.04]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.631497, training avg acc 0.312916\n",
      "epoch 12, testing avg loss 5.996764, testing avg acc 0.163392\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.4, cost=2.86]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.76it/s, accuracy=0.199, cost=6.18]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.544593, training avg acc 0.324217\n",
      "epoch 13, testing avg loss 6.089913, testing avg acc 0.161801\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.427, cost=2.66]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.87it/s, accuracy=0.199, cost=6.3] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.468694, training avg acc 0.334358\n",
      "epoch 14, testing avg loss 6.099215, testing avg acc 0.157838\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:56<00:00,  2.01it/s, accuracy=0.477, cost=2.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.76it/s, accuracy=0.161, cost=6.41]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.391473, training avg acc 0.345539\n",
      "epoch 15, testing avg loss 6.251027, testing avg acc 0.155682\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.442, cost=2.63]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.78it/s, accuracy=0.151, cost=6.42]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.330153, training avg acc 0.354420\n",
      "epoch 16, testing avg loss 6.309449, testing avg acc 0.152618\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:58<00:00,  2.01it/s, accuracy=0.467, cost=2.62]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.76it/s, accuracy=0.172, cost=6.33]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.266581, training avg acc 0.364243\n",
      "epoch 17, testing avg loss 6.273650, testing avg acc 0.151396\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:30<00:00,  2.08it/s, accuracy=0.493, cost=2.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.12it/s, accuracy=0.167, cost=6.59]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.198412, training avg acc 0.374924\n",
      "epoch 18, testing avg loss 6.435645, testing avg acc 0.152726\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:16<00:00,  2.12it/s, accuracy=0.491, cost=2.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.18it/s, accuracy=0.172, cost=6.6] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.142262, training avg acc 0.383919\n",
      "epoch 19, testing avg loss 6.533607, testing avg acc 0.155918\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [12:16<00:00,  2.12it/s, accuracy=0.509, cost=2.29]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:07<00:00,  5.11it/s, accuracy=0.194, cost=6.55]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.101646, training avg acc 0.389956\n",
      "epoch 20, testing avg loss 6.645807, testing avg acc 0.151603\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [04:35<00:00,  6.88s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.05320787"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
